#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import jsonify, request
from flask_restful import Resource
from utility.odoo_manager import OdooManager  # 操作odoo的单例
from utility.error_code import error_code  # 异常代码
from utility.message_manager import MessageBusManager
from event import event_type
from datetime import datetime, timedelta
from command import command
import logging,os
from utility import tools
from settings  import DOWN_FILE_DIR
from utility.file_split import split_file
from utility.memcache_manager import MemcacheManager
import pandas as pd

FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)


class HighRiskProListAPI(Resource):
    """
    高危专案管理首页下部列表
    :request: post
    :param status: 状态 0 管理中 1 已结案
    :param gwColorCode: 高危颜色
    :param jdjg: 建档机构
    :param jdlx: 建档类型 1 本院建档 2外院建档
    :param mcyjStartdate: 末次月经时间-开始时间
    :param mcyjEnddate: 末次月经时间-结束时间
    :param searchText: 搜索字符串
    :param isAsc：排序方向 排序的方向,示例值(asc,desc)
    :param orderByColumn：排序列
    :param pageNum：当前页数
    :param pageSize: 分页大小
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            is_asc = params.get('isAsc') if params.get('isAsc', False) else 'asc'
            order_by_column = params.get('orderByColumn') if params.get('orderByColumn', False) else 'create_date'
            #  构造排序方式
            order_ =  order_by_column+' '+ is_asc
            #  初始化页数,返回数据条数,偏移
            page = int(params.get('pageNum')) if params.get('pageNum', False) else 1
            pagesize = int(params.get('pageSize')) if params.get('pageSize', False) else 10
            offset = page * pagesize - pagesize
            #  构造查询条件 status
            query_ = [
                ('max_gwys', 'in', ['2', '3', '4', '5', '6', '7'])
            ]
            if params.get('status'): # 状态 null 全部 0 管理中 1 已结案
                query_.append(('status', '=', str(params.get('status'))))
            if params.get('gwColorCode'): # 高危颜色
                query_.append(('max_gwys', '=', params.get('gwColorCode')))
            if params.get('jdjg'): # 建档机构
                query_.append(('jd_dw', '=', int(params.get('jdjg'))))
            if params.get('jdlx'): # 建档类型 null 全部 1 本院建档 2外院建档
                query_.append(('jd_sfby', '=', params.get('jdlx')))
            if params.get('mcyjStartDate'): # 末次月经开始时间
                query_.append(('mcyjsj', '>=', params.get('mcyjStartdate')))
            if params.get('mcyjEndDate'): # 末次月经结束时间
                query_.append(('mcyjsj', '<=', params.get('mcyjEndDate')))
            if params.get('searchText'): # 搜索字符串
                query_.append(('mq_xm', 'ilike', params.get('searchText')))  # 孕妇姓名
                query_.append(('mq_sjhm', 'ilike', params.get('searchText'))) # 孕妇手机号码
            fields = [
                    'img_url','mzh','mq_xm','mq_cz_address','mq_mz',
                    'mq_age','max_gwys','yz','jd_dw',
                    'sccjrq','jd_date','status', 'id'
                    ]    
            res_archives = odoo.env['res.archives'].search_read(query_,fields,  offset = offset, limit = pagesize, order = order_)
            data_ = []
            for  res_archives_ in res_archives:
                data_tmp={
                    'imgUrl': res_archives_['img_url'],
                    'mzh': res_archives_['mzh'],
                    'mqXm': res_archives_['mq_xm'],
                    'mqZz': res_archives_['mq_cz_address'],
                    'mqMz': res_archives_['mq_mz'],
                    'mqAge': res_archives_['mq_age'],
                    'yz': tools.parase_yz(1, res_archives_['yz']),
                    'gwColorCode': res_archives_['max_gwys'],
                    'sccjsj': res_archives_['sccjrq'],
                    'zggwys': res_archives_['max_gwys'],
                    'jdjgCode': res_archives_['jd_dw'][0] if res_archives_['jd_dw'] else None,
                    'jdjgName': res_archives_['jd_dw'][1] if res_archives_['jd_dw'] else None,
                    'jdsj': res_archives_['jd_date'],
                    'status': res_archives_['status'],
                    'id': res_archives_['id']
                }
                data_.append(data_tmp)
            total_ = odoo.env['res.archives'].search_count(query_)    
            return jsonify({'code': 0, 'msg': 'success', 'data': {'rows': data_,'total': total_}, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class HighRiskProExportAPI(Resource):
    """
    导出高危专案管理首页下部列表
    :request: post
    :param status: 状态 0 管理中 1 已结案
    :param gwColorCode: 高危颜色
    :param jdjg: 建档机构
    :param jdlx: 建档类型 1 本院建档 2外院建档
    :param mcyjStartdate: 末次月经时间-开始时间
    :param mcyjEnddate: 末次月经时间-结束时间
    :param searchText: 搜索字符串
    :returns: json string
    """
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            #获取UID
            uid = params.get('uid')
            # 防重校验
            cache = MemcacheManager()
            check = cache.get('highriskpro'+str(uid))
            if check:
                check = check.split(',')
                data_ ={
                        'blob': str(open(check[0], 'rb').read()),
                        'isOver': 0 #0否 1是
                    }
                if len(check)==1:
                    data_['isOver'] = 1   
                    cache.delete('highriskpro'+str(uid)) 
                else:    
                    check = check[1:]    
                    cache.set('highriskpro'+str(uid), ','.join(check))
                return {
                    'code': 0,
                    'data': data_,
                    'msg': 'success',
                } 
            #  构造查询条件 status
            query_ = [
                ('max_gwys', 'in', ['2', '3', '4', '5', '6', '7'])
            ]
            if params.get('status'): # 状态 null 全部 0 管理中 1 已结案
                query_.append(('status', '=', str(params.get('status'))))
            if params.get('gwColorCode'): # 高危颜色
                query_.append(('max_gwys', '=', params.get('gwColorCode')))
            if params.get('jdjg'): # 建档机构
                query_.append(('jd_dw', '=', int(params.get('jdjg'))))
            if params.get('jdlx'): # 建档类型 null 全部 1 本院建档 2外院建档
                query_.append(('jd_sfby', '=', params.get('jdlx')))
            if params.get('mcyjStartDate'): # 末次月经开始时间
                query_.append(('mcyjsj', '>=', params.get('mcyjStartdate')))
            if params.get('mcyjEndDate'): # 末次月经结束时间
                query_.append(('mcyjsj', '<=', params.get('mcyjEndDate')))
            if params.get('searchText'): # 搜索字符串
                query_.append(('mq_xm', 'ilike', params.get('searchText')))  # 孕妇姓名
                query_.append(('mq_sjhm', 'ilike', params.get('searchText'))) # 孕妇手机号码
            fields = [
                    'img_url','mzh','mq_xm','mq_cz_address','mq_mz',
                    'mq_age','max_gwys','yz','jd_dw',
                    'sccjrq','jd_date','status', 'id'
                    ]  
            res_archives = odoo.env['res.archives'].search_read(query_,fields)
            data_ = []
            for  res_archives_ in res_archives:
                data_tmp={
                    '序号': res_archives_['id'],
                    '母亲头像图标URL': res_archives_['img_url'],
                    '门诊号': res_archives_['mzh'],
                    '母亲姓名': res_archives_['mq_xm'],
                    '母亲常住地址': res_archives_['mq_cz_address'],
                    '民族': res_archives_['mq_mz'],
                    '年龄': res_archives_['mq_age'],
                    '孕周': tools.parase_yz(1, res_archives_['yz']),
                    '高危颜色': res_archives_['max_gwys'],
                    '上次产检时间': res_archives_['sccjrq'],
                    '最高高危颜色': res_archives_['max_gwys'],
                    '建档机构编码': res_archives_['jd_dw'][0] if res_archives_['jd_dw'] else None,
                    '建档机构名称': res_archives_['jd_dw'][1] if res_archives_['jd_dw'] else None,
                    '建档时间': res_archives_['jd_date'],
                    'status': res_archives_['status'],
                    
                }
                data_.append(data_tmp)
            res = {'blob':'','isOver':'1'}
            #print (res)
            if data_:
                col_names=[
                    '序号','母亲头像图标URL','门诊号','母亲姓名','母亲常住地址','民族','年龄',
                    '孕周','高危颜色','上次产检时间','最高高危颜色','建档机构编码',
                    '建档机构名称','建档时间','状态'
                ]
                df=pd.DataFrame(data_)
                file_path='{}{}-{}-0.xlsx'.format(DOWN_FILE_DIR,'高危专案列表',uid)
                df.to_excel(file_path,columns=col_names,index=False)
                file_path_n = split_file('{}-{}-0.xlsx'.format('高危专案列表',uid),col_names)
                #初始文件小于3M
                if file_path == file_path_n[0]:
                    res['blob'] = str(open(file_path, 'rb').read())
                    os.remove(file_path)
                else:
                    res['blob'] = str(open(file_path_n[0], 'rb').read()) 
                    os.remove(file_path_n[0])
                    res['isOver'] = '0'
                    #文件大于3M
                    req_flag = ','.join(file_path_n[1:])
                    #文件名保存到缓存里
                    cache.set('highriskpro'+str(uid), req_flag)
            #print (res)
            return jsonify({'code': 0, 'msg': 'success', 'data': res})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})


class HighRiskProStaGetAPI(Resource):
    def get(self):
        return {}